# -*- coding: utf-8 -*-

'''
Created on 09-08-24

@author: peterd
'''

from web.service.LBCParser import LBCParser
from infra.logging import logger
from geo.models import NoSuchCity, NoSuchStreet, NoSuchLocation


class OrgListParser(LBCParser):

	def __init__(self, lbcategory, dataProcessor): 
		LBCParser.__init__(self, lbcategory, dataProcessor)
		
		self.orgs_ = {}
		self.inOrg_ = False	
		
				
	def reset__(self):
		self.inOrg_ = False
		self.orgs_.clear()
		
		
		
	# TODO: move to base
	def parse(self, htmlPage):
		self.reset__()
		log = logger.getLogger()
		log.info("Parsing page content ...")
		self.feed(htmlPage)
		self.close()
		log.info("Content parsed.")
		return self.orgs_
		

	def start_span(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'xr_product_title':
				self.inOrg_ = True
				break


	def end_span(self):
		if self.inOrg_:
			self.inOrg_ = False
			
			
	def start_a(self, attrs):
		for attr, value in attrs:
			'''
			if attr == 'href' and value == '#next':
				self.inNextPage_ = True
				break
			'''
			
			if self.inOrg_ and attr == 'href':
				self.orgUrl_ = value
				break
			
	
	def end_e(self):
		if self.inNextPage_:
			self.inNextPage_ = False
				
	
	def handle_data(self, data):
		if self.inOrg_ and self.dataProcessor_.match(data):
			self.orgs_[data] = self.orgUrl_
			
			
	def getId(self):
		return self.__class__.__name__




class OrgParser(LBCParser):

	def __init__(self, lbcategory, name, url): 
		LBCParser.__init__(self, lbcategory, None, parsedUrl = url)
		
		self.name_ = name
		self.url_ = url
		
		self.inAddr_ = False
		self.addr_ = ''
		
		
	def reset__(self):
		self.inAddr_ = False
		self.addr_ = ''
		
		LBCParser.reset__(self)
				
		
	def handle_data(self, data):
		if self.inAddr_:
			self.addr_ += data + ' '
	
		if data.find('Adresa:') != -1:
			self.inAddr_ = True
					
		if data.find(u'Telefón:') != -1 and self.inAddr_:	
			self.tryCreateOrganization(self.addr_, self.addr_)
			
						
	def tryCreateOrganization(self, street, city):
		log = logger.getLogger()
		try:
			self.setCity(city)
			self.setStreet(street)
			self.createOrganization(name = self.name_, url = self.url_)					
		except NoSuchCity, e:
			log.error('NoSuchCity exception caught, reason: %s' % e)						
		except NoSuchStreet, e:
			log.error('NoSuchStreet exception caught, reason: %s' % e)
		except NoSuchLocation, e:
			log.error('NoSuchLocation exception caught, reason: %s' % e)
		except Exception, e:
			log.error('An exception caught, reason: %s' % e)
					
		self.reset__()

						
	def getId(self):
		return self.__class__.__name__